package cn.j0n4than.accountingtool.interceptor;

import cn.j0n4than.accountingtool.utils.DesUtil;
import cn.j0n4than.accountingtool.utils.RedisUtil;
import cn.j0n4than.accountingtool.utils.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器基类
 *
 * @author jonathan
 */
public class BaseInterceptor {

    /**
     * jackson
     */
    protected final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 加密工具类
     */
    protected final DesUtil desUtil = new DesUtil();

    /**
     * redis工具类
     */
    @Autowired
    protected RedisUtil redisUtil;

    /**
     * 未授权响应
     *
     * @param response HttpServletResponse
     * @return boolean
     */
    protected boolean unauthorized(HttpServletResponse response) {
        try {
            String json = this.objectMapper.writeValueAsString(Response.error().setMessage("unauthorized").setStatus(401));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(401);

            response.getWriter().write(json);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
